package com.bysj.lms.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.bysj.lms.pojo.dto.CourseDto;
import com.bysj.lms.pojo.entity.Class;
import com.bysj.lms.pojo.entity.Course;
import com.bysj.lms.mapper.CourseMapper;
import com.bysj.lms.pojo.entity.DictionaryItem;
import com.bysj.lms.service.IClassService;
import com.bysj.lms.service.ICourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bysj.lms.service.IDictionaryItemService;
import com.bysj.lms.utils.StringUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaojiakai
 * @since 2022-04-16
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    
    @Autowired
    CourseMapper courseMapper;
    
    
    
    @Override
    public boolean adds(List<Course> list) {
        System.out.println(list);
        int save = courseMapper.adds(list);
        System.out.println(save);
        return save > 0 ?true:false;
    }
    
    @Override
    public List<Course> list(Integer classId, String term) {
        List<Course> list = lambdaQuery().eq(Course::getClassId, classId)
                .eq(Course::getTerm, term).list();
        return list;
    }
    
    @Override
    public void export(HttpServletResponse response, String filename,Integer classId,String term) throws IOException {
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Access-Control-Expose-Headers","Content-disposition");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + filename + ".xlsx");
    
        /**
         * 样式策略
         */
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 12);
        headWriteCellStyle.setWriteFont(headWriteFont);
    
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setColor(IndexedColors.BLUE_GREY.getIndex());
//        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        contentWriteFont.setFontHeightInPoints((short) 8);
//        contentWriteCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
//        contentWriteCellStyle.setFillBackgroundColor(IndexedColors.BLUE.getIndex());
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setWrapped(true);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        
        //写入数据
        List<Course> list = list(classId, term);
        List<List<String>> data = new ArrayList<>();
        for(int i=1;i<=11;i++){
            List<String> row = new ArrayList<>();
            row.add("第"+i+"节");
            int ii=i;
            List<Course> courseList = list.stream().filter(course -> course.getSection() == ii).collect(Collectors.toList());
            Map<Integer,String> map = new HashMap<>();
            courseList.forEach(course -> {
                String content = "";
                if(map.containsKey(course.getWeek())){
                    content = map.get(course.getWeek()) +"\n\n"+ course.getCourseName() + "\n" +
                            "教师：" + course.getTeacher() + "\n" +
                            "周次：" + course.getWeekTime() + "\n" +
                            "教室：" + course.getClassroom();
                }else{
                    content = course.getCourseName() + "\n" +
                            "教师：" + course.getTeacher() + "\n" +
                            "周次：" + course.getWeekTime() + "\n" +
                            "教室：" + course.getClassroom();
                }
                map.put(course.getWeek(),content);
            });
            for(int j=1;j<=7;j++){
                row.add(map.get(j));
            }
            data.add(row);
            System.out.println(row);
            System.out.println(row.size());
        }
        
        EasyExcel.write(response.getOutputStream())
                // 这里放入动态头
                .head(head()).sheet("课表")
//                .registerWriteHandler(new ExportCellWriteHandler())
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(16))
                .doWrite(data);
    }
    
    @Override
    public List<List<String>> head() {
        List<List<String>> head = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<>();
        head0.add("节次/周次");
        List<String> head1 = new ArrayList<>();
        head1.add("星期一");
        List<String> head2 = new ArrayList<>();
        head2.add("星期二");
        List<String> head3 = new ArrayList<>();
        head3.add("星期三");
        List<String> head4 = new ArrayList<>();
        head4.add("星期四");
        List<String> head5 = new ArrayList<>();
        head5.add("星期五");
        List<String> head6 = new ArrayList<>();
        head6.add("星期六");
        List<String> head7 = new ArrayList<>();
        head7.add("星期日");
        head.add(head0);
        head.add(head1);
        head.add(head2);
        head.add(head3);
        head.add(head4);
        head.add(head5);
        head.add(head6);
        head.add(head7);
        return head;
    }

    @Override
    public List<CourseDto> getSC(String tid, String term,String tname) {
        List<CourseDto> list = courseMapper.getSC(tid,term,tname);
        return list;
    }
}
